#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Project: devops
#  Author: an00
#  Create: 2018/7/3 19:51

"""
自定义搜索示例，使用django-filter模块
"""

import django_filters
from django.db.models import Q
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
User = get_user_model()


class UserFilter(django_filters.FilterSet):
    """
    name对应关联的field，这里的lookup_expr表达式代表是模糊查询，可以使用其他表达式
    method传入一个自定义过滤函数，传入值返回函数过滤的内容
    """
    username = django_filters.CharFilter(name='username', lookup_expr='icontains')
    groups = django_filters.CharFilter(name='groups', lookup_expr='exact')
    role = django_filters.CharFilter(name='role', lookup_expr='exact')
    mix_info = django_filters.CharFilter(method='multi_filter')

    @staticmethod
    def multi_filter(queryset, name, value):
        return queryset.filter(Q(username__icontains=value) | Q(email__icontains=value))

    class Meta:
        model = User
        fields = ['username', ]


class GroupFilter(django_filters.FilterSet):
    """
    用户组字段搜索
    """
    name = django_filters.CharFilter(name='name', lookup_expr='icontains')

    class Meta:
        model = Group
        fields = ['name', ]
